"""
基础内容生成器
"""

from abc import ABC, abstractmethod
from typing import Dict, Any, List
import re
from pathlib import Path

from ..core.config import get_settings
from ..core.logger import app_logger

settings = get_settings()


class BaseGenerator(ABC):
    """内容生成器基类"""
    
    def __init__(self):
        self.sensitive_words = self._load_sensitive_words()
    
    def _load_sensitive_words(self) -> List[str]:
        """加载敏感词列表"""
        try:
            sensitive_file = Path(settings.SENSITIVE_WORDS_PATH)
            if sensitive_file.exists():
                with open(sensitive_file, 'r', encoding='utf-8') as f:
                    words = [line.strip() for line in f if line.strip()]
                app_logger.info(f"加载敏感词 {len(words)} 个")
                return words
            else:
                app_logger.warning("敏感词文件不存在")
                return []
        except Exception as e:
            app_logger.error(f"加载敏感词失败: {e}")
            return []
    
    def filter_sensitive_content(self, content: str) -> bool:
        """检查内容是否包含敏感词"""
        for word in self.sensitive_words:
            if word.lower() in content.lower():
                app_logger.warning(f"内容包含敏感词: {word}")
                return False
        return True
    
    def format_for_platform(self, content: str, platform: str) -> Dict[str, Any]:
        """为特定平台格式化内容"""
        
        platform_configs = {
            "weibo": {
                "max_length": 140,
                "hashtag_format": "#{tag}#",
                "style": "casual"
            },
            "twitter": {
                "max_length": 280,
                "hashtag_format": "#{tag}",
                "style": "concise"
            },
            "wechat": {
                "max_length": 1000,
                "hashtag_format": "",
                "style": "formal"
            }
        }
        
        config = platform_configs.get(platform, platform_configs["weibo"])
        
        # 截断内容
        if len(content) > config["max_length"]:
            content = content[:config["max_length"] - 3] + "..."
        
        return {
            "content": content,
            "platform": platform,
            "config": config
        }
    
    @abstractmethod
    async def generate(self, trend_data: Dict[str, Any], platform: str, style: str = "default") -> Dict[str, Any]:
        """生成内容的抽象方法"""
        pass